package com.new1cloud.file.tools;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.attribute.BasicFileAttributes;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;

/**
 * 文件唯一码生成
 */
public class FileHashGenerate {

    /**
     * 生成file的MD5值
     * @param file file对象
     * @return
     */
    public static String genHashByBytes(File file) {
        MessageDigest digest = getDigestInstance();
        if(Objects.isNull(digest)) {
            return null;
        }
        try (FileInputStream fis = new FileInputStream(file)) {
            byte[] byteArray = new byte[1024];
            int bytesCount;
            while ((bytesCount = fis.read(byteArray)) != -1) {
                digest.update(byteArray, 0, bytesCount);
            }
            return bytesToHex(digest.digest());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static MessageDigest getDigestInstance() {
        try {
            return MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte aByte : bytes) {
            sb.append(String.format("%02x", aByte));
        }
        return sb.toString();
    }

    /**
     * 结合文件的大小、最后修改时间等属性生成唯一标识
     * @param file file对象
     * @return
     */
    public static String genHashByAttributes(File file) {
        try {
            BasicFileAttributes attrs = getFileAttributes(file);
            return attrs.lastModifiedTime().toMillis() + "_" + attrs.size();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private static BasicFileAttributes getFileAttributes(File file) throws IOException {
        return java.nio.file.Files.readAttributes(file.toPath(), BasicFileAttributes.class);
    }


}
